const network = require("../manager/network-manager.js");
const dialog = require("./dialog.js");


// #ifdef APP-PLUS
const shanYanSDKModule = uni.requireNativePlugin('CLSDK-ShanYanSDKModule'); //调用
// #endif
import uiConfig from '@/login-ui-config.js'

var QQMapWX = require('./qqmap-wx-jssdk.min.js');
var qqmapsdk = new QQMapWX({
	key: 'OXRBZ-FMSCP-XFSD2-VJGTG-HOLVZ-6JF5C' // 必填
});

function isLogin(app) {

	if (app.globalData.userInfo != null && typeof app.globalData.userInfo === 'object') {
		return true;
	} else {
		return false;
	}
}

function timeFrom(dateTime = null, format = 'yyyy-mm-dd') {
	var format = format || 'yyyy-mm-dd'
	var timestamp = Number(Date.parse(dateTime))

	let timer = (Number(new Date()) - timestamp) / 1000;
	// 如果小于5分钟,则返回"刚刚",其他以此类推
	// console.log(timer,'----')
	let tips = '';
	switch (true) {
		case timer < 300:
			tips = '刚刚';
			break;
		case timer >= 300 && timer < 3600:
			tips = parseInt(timer / 60) + '分钟前';
			break;
		case timer >= 3600 && timer < 86400:
			tips = parseInt(timer / 3600) + '小时前';
			break;
		case timer >= 86400 && timer < 86400 * 3:
			tips = parseInt(timer / 86400) + '天前';
			break;
		default:
			// 如果format为false，则无论什么时间戳，都显示xx之前
			if (format === false) {
				if (timer >= 2592000 && timer < 365 * 86400) {
					tips = parseInt(timer / (86400 * 30)) + '个月前';
				} else {
					tips = parseInt(timer / (86400 * 365)) + '年前';
				}
			} else {
				tips = moment(dateTime).format('YYYY-MM-DD')
			}
	}
	return tips;
}

function jumpLogin(from) {
	// #ifdef APP-PLUS
	// mobileLogin();
	if (shanYanSDKModule) {
		console.log("原生走阿里一键登录");
		uni.showLoading({
			title: "获取登录方式"
		})
		if (plus.os.name == "iOS") {
			//闪验SDK 预取号
			shanYanSDKModule.preGetPhonenumber((complete) => {
				// uni.hideLoading();
				console.log(JSON.stringify(complete));
			});
		} else {
			//闪验SDK 预取号
			shanYanSDKModule.getPhoneInfo((result) => {
				// uni.hideLoading();
				console.log(JSON.stringify(result));
			});
		}
		aliLogin(from);
	} else {
		//不存在手机号登录sdk直接验证码登录
		mobileLogin(from);
	}
	// #endif
	// #ifdef H5
	mobileLogin(from);
	// #endif

	// #ifdef MP-WEIXIN
	wechatLogin(from);
	// #endif
}
// 阿里手机号码识别登录
function aliLogin(from) {
	const config = uiConfig.buildFullscreen();
	let platform = uni.getSystemInfoSync().platform;
	// console.log("config："+JSON.stringify(config));

	if (platform == 'android') {
		//Android 弹窗模式
		shanYanSDKModule.setAuthThemeConfig(config, result => {
			console.log("闪验：" + JSON.stringify(result));
			//授权页添加自定义控件元素点击事件监听                    
			if (result.result == 'customView_3' || result.result == 'customView_1') {
				shanYanSDKModule.finishAuthActivity();
				mobileLogin(from)
			}
		});
		//闪验SDK  拉起授权页方法 isFinish
		shanYanSDKModule.openLoginAuth(false,
			result => {
				uni.hideLoading();
				if (result.code != 1000) {
					shanYanSDKModule.finishAuthActivity();
					mobileLogin(from)
					console.log("拉起授权页失败：" + JSON.stringify(result));
				} else {
					console.log("拉起授权页成功：" + JSON.stringify(result));
				}
			},
			result => {
				console.log("闪验：" + JSON.stringify(result));
				registerWithMobileToken(result, from);
			});
	} else {
		//一键登录
		shanYanSDKModule.quickAuthLoginWithConfigure(config,
			openLoginAuthListenerResult => {
				//拉起授权页面回调
				uni.hideLoading();
				if (openLoginAuthListenerResult.code != 1000) {
					shanYanSDKModule.finishAuthControllerCompletion(oneKeyLoginListenerResult => {});
					mobileLogin(from)
					console.log("拉起授权页失败：" + JSON.stringify(openLoginAuthListenerResult));
				} else {
					console.log("拉起授权页成功：" + JSON.stringify(openLoginAuthListenerResult));
				}
			},
			oneKeyLoginListenerResult => {
				registerWithMobileToken(oneKeyLoginListenerResult, from);
			});

		//设置自定义控件点击回调，返回信息带有widgetId
		shanYanSDKModule.setCustomInterface((customInterface) => {
			console.log("闪验：" + JSON.stringify(customInterface));
			//授权页添加自定义控件元素点击事件监听                    
			if (customInterface.widgetId == 'mobile_login_button') {
				shanYanSDKModule.finishAuthControllerCompletion(oneKeyLoginListenerResult => {});
				mobileLogin(from)
			}
		});
	}

}

function registerWithMobileToken(tokenResult, from) {
	console.log("registerWithMobileTokenL" + JSON.stringify(tokenResult));
	console.log(from);

	let platform = uni.getSystemInfoSync().platform;

	// 
	if (1011 == tokenResult.code) {
		uni.hideLoading();
		console.log("点击返回按钮")
	} else if (1000 == tokenResult.code) {
		console.log("获取Token成功，接下来拿着结果里面的Token去服务端换取手机号码，SDK服务到此结束")
		const app = getApp();
		var result = {};
		if (platform == 'android') {
			result = JSON.parse(tokenResult.result);
		} else {
			result = tokenResult.data;
		}
		var that = this;


		var loginType = "";
		if (app.globalData.systemPlatform == "WEIXIN") {
			loginType = "0"
		} else if (app.globalData.systemPlatform == "App") {
			loginType = "1"
		}
		var loginDevice = ""
		if (app.globalData.systemVersionNum.indexOf("Android") != -1) {
			loginDevice = "0"
		}

		if (app.globalData.systemVersionNum.indexOf("iOS") != -1) {
			loginDevice = "1"
		}






		var uri = app.globalData.config.interfaces.URL_SYS_ALI_MOBILE_LOGIN;
		var params = {
			token: result.token,
			platform: platform,

			loginType: loginType, //登录来源(0 小程序 1 用户app 2 渠道端 3 pc)
			loginDevice: loginDevice, //登录设备(0 Android 1 IOS)
			loginVersion: uni.getStorageSync("version")
		};
		network.get(uri, params, 'form').then(res => {
			console.log(res);
			uni.hideLoading();
			if (res.code == 200) {
				//手动关闭授权页
				if (platform == 'android') {
					shanYanSDKModule.finishAuthActivity();
				} else {
					shanYanSDKModule.finishAuthControllerCompletion();
				}
				//保存用户信息
				app.saveUser(res.data);
				app.saveToken(res.data.token);
				//未完善信息跳转到完善信息
				goBackSourcePageFix(from, true);

			} else {
				dialog.toast(res.message);
				setTimeout(function() {
					if (platform == 'android') {
						shanYanSDKModule.finishAuthActivity();
					} else {
						shanYanSDKModule.finishAuthControllerCompletion();
					}
				}, 2000);

			}
		}).catch(res => {
			uni.hideLoading();
			dialog.toast("登录失败");
			console.error(res)
			setTimeout(function() {
				if (platform == 'android') {
					shanYanSDKModule.finishAuthActivity();
				} else {
					shanYanSDKModule.finishAuthControllerCompletion();
				}
			}, 2000);
		});

	} else {
		//其他失败情况，手动关闭授权页
		//手动关闭授权页
		if (platform == 'android') {
			shanYanSDKModule.finishAuthActivity();
		} else {
			shanYanSDKModule.finishAuthControllerCompletion();
		}
		mobileLogin(from);
		console.log("getLoginToken" + JSON.stringify(tokenResult))
	}
}

function mobileLogin(from) {
	uni.navigateTo({
		url: '/pages/user/login?from=' + from
	});
}

function wechatLogin(from) {
	// uni.setStorageSync('from',from)
	// uni.switchTab({
	// 	url:"/module_my/pages/my",
	// 	fail(err) {
	// 		console.log(err, 'err')
	// 	}
	// })
	uni.navigateTo({
		url: '/pages/user/weChatPromptLogin?from=' + from
	});
}

function createUidKey(key = '') {
	const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
		let r = (Math.random() * 16) | 0;
		let v = c == 'x' ? r : (r & 0x3) | 0x8;
		return v.toString(16);
	});
	return key + uuid;
}


function endWiths(str, suffix) {
	var d = str.length - suffix.length;
	return (d >= 0 && str.lastIndexOf(suffix) == d)
}


/**
 * 对比版本号，如需要，请自行修改判断规则
 * 支持比对	("3.0.0.0.0.1.0.1", "3.0.0.0.0.1")	("3.0.0.1", "3.0")	("3.1.1", "3.1.1.1") 之类的
 * @param {Object} v1
 * @param {Object} v2
 * v1 > v2 return 1
 * v1 < v2 return -1
 * v1 == v2 return 0
 */
function compareVersion(v1 = '0', v2 = '0') {
	v1 = String(v1).split('.')
	v2 = String(v2).split('.')
	const minVersionLens = Math.min(v1.length, v2.length);

	let result = 0;
	for (let i = 0; i < minVersionLens; i++) {
		const curV1 = Number(v1[i])
		const curV2 = Number(v2[i])

		if (curV1 > curV2) {
			result = 1
			break;
		} else if (curV1 < curV2) {
			result = -1
			break;
		}
	}

	if (result === 0 && (v1.length !== v2.length)) {
		const v1BiggerThenv2 = v1.length > v2.length;
		const maxLensVersion = v1BiggerThenv2 ? v1 : v2;
		for (let i = minVersionLens; i < maxLensVersion.length; i++) {
			const curVersion = Number(maxLensVersion[i])
			if (curVersion > 0) {
				v1BiggerThenv2 ? result = 1 : result = -1
				break;
			}
		}
	}
	return result;

}

function getCurrPage() {
	try {
		let pages = getCurrentPages();
		if (pages.length) {
			return pages[pages.length - 1];
		}
	} catch (e) {}
	return undefined;
}

function getNavigationBarTitle() {
	let page = getCurrPage();
	if (page) {
		let view = page.$holder;
		if (view) {
			// h5  
			return view.navigationBar.titleText;
		} else {
			// app-plus  
			try {
				view = page.$getAppWebview();
				if (view) {
					const style = view.getStyle()
					if (style && style.titleNView) {
						return style.titleNView.titleText;
					}
				}
			} catch (e) {
				if (process.env.NODE_ENV !== 'production') {
					console.log('getCurrentPages is not ready')
				}
			}
		}
	}
	return undefined;
}

function subYMD(val) {
	console.log(val);

	if (val == null || val == undefined) {
		return '';
	}

	return val.substring(0, 10);
}

function subHMS(val) {
	console.log(val);

	if (val == null || val == undefined) {
		return '';
	}

	console.log("xxxx" + val.substring(10, 11));
	return val.substring(10, 11);
}

function getLocation(successCallBack) {
	let that = this;
	uni.getLocation({
		type: 'gcj02',
		// type: 'wgs84',
		success: function(res) {
			let latitude = res.latitude;
			let longitude = res.longitude;
			let speed = res.speed;
			let accuracy = res.accuracy;
			successCallBack(res);
		}
	});
}

function bannerJump(val) {
	console.log(val);
	switch (val.toTypeDicId) {
		case '2': //文章
			uni.navigateTo({
				url: "/module_community/pages/article/detail/detail?isFromOpenPage=1&id=" + val.relationId
			})
			break
		case '3': //外部链接
			uni.navigateTo({
				url: "/pages/webView/webView?isFromOpenPage=1&url=" + val.linkUrl
			})
			break
		case '4': //爱车
			uni.switchTab({
				url: "/pages/car/myLoveCar/myLoveCar?isFromOpenPage=1"
			})
			break
		case '5': //预约试驾
			uni.navigateTo({
				url: "/module_car/pages/testDrive/testDrive?isFromOpenPage=1&"
			})
			break
		case '6': //长图
			console.log(val)
			uni.navigateTo({
				url: "/pages/advertisement/advertisement?isFromOpenPage=1&url=" + val.relationImage,
				fail: (e) => {
					console.log(e);
				}
			})

			break
		case '7': //问答
			console.log(val)
			uni.navigateTo({
				url: "/module_community/pages/questionAndAnswer/detail/detail?id=" + val.answerId,
				fail: (e) => {
					console.log(e);
				}
			})

			break
		case '9': 
			console.log(val)
			uni.navigateTo({
				url: "/module_car/pages/stores/storeList",
				fail: (e) => {
					console.log(e);
				}
			})

			break
		case '10': //问答
			console.log(val)
			uni.navigateTo({
				url: "/module_community/pages/article/detail/detail?isLocalResources=true&id=" + val.localId,
				fail: (e) => {
					console.log(e);
				}
			})

			break
		case '11': //商城
			console.log(val)
			uni.navigateTo({
				url: "/module_mall/goodsDetail/goodsDetail?goodid=" + val.commodityId,
				fail: (e) => {
					console.log(e);
				}
			})
		
			break
		case '12': //秒杀
			console.log(val)
			uni.navigateTo({
				url: "/module_mall/goodsDetail/goodsDetail?goodid=" + val.seckillId + '&isSeckill=true',
				fail: (e) => {
					console.log(e);
				}
			})
		
			break
		case '0': //无
			console.log("toTypeDicId == 0");
			break
	}
}
// 小程序返回
function gotBackSourePageMini(from) {
	if (from == 'moments') {
		uni.setStorageSync('from', "")
		uni.redirectTo({
			url: "/module_community/pages/moments/moments"
		})
	} else if (from == 'article') {
		uni.setStorageSync('from', "")
		uni.redirectTo({
			url: '/module_community/pages/article/article'
		})
	} else if (from == 'activity') {
		uni.setStorageSync('from', "")
		uni.redirectTo({
			url: '/module_community/pages/activity/activity'
		})
	} else if (from == 'myAppointment') { //我的预约
		uni.redirectTo({
			url: "/module_my/pages/myAppointment/myAppointment"
		})
	} else if (from == 'wishList') { //心愿单
		uni.redirectTo({
			url: "/module_my/pages/wishList/wishList"
		})
	} else if (from == 'myorderHome') { //我的订单
		uni.redirectTo({
			url: "/module_my/myorderHome/myorderHome"
		})
	} else if (from == 'orderList') { //我的订单
		uni.redirectTo({
			url: "/module_my/pages/orderList/orderList"
		})
	} else if (from == 'myCarList') { //我的爱车
		uni.redirectTo({
			url: "/module_car/myCarList/myCarList"
		})
	} else if (from == 'personalCenter') { //发布去个人中心
		uni.redirectTo({
			url: "/module_my/pages/personalCenter/personalCenter"
		})
	} else if (from == 'following') { //跳转我的关注
		uni.redirectTo({
			url: "/module_my/pages/following"
		})
	} else if (from == 'follower') { //跳转粉丝
		uni.redirectTo({
			url: "/module_my/pages/follower"
		})
	} else if (from == 'myAddress') { //跳转我的地址
		uni.redirectTo({
			url: "/module_my/pages/myAddress/myAddress"
		})
	} else {
		uni.navigateBack({
			changed: true
		}); //返回上一页

	}

}

function goBackSourcePage(from) {
	goBackSourcePageFix(from, false)
}

function redirectToFix(info, isOneKeyLogin) {
	//手机号免认证登录后需要navigation跳转
	if (isOneKeyLogin) {
		uni.navigateTo(info)
	} else {
		uni.redirectTo(info)
	}
}
// 返回来源页面
function goBackSourcePageFix(from, isOneKeyLogin) {
	// wx.redirectTo(OBJECT) 关闭当前页面，跳转到应用内的某个页面。
	// wx.navigateTo(OBJECT)
	const app = getApp();
	console.log("goBackSourcePage：" + from);
	// 未完善信息 完善信息
	if (app.globalData.userInfo.userName == "" || app.globalData.userInfo.userName ==
		null || app.globalData.userInfo.userName == "lsojvke") {
		console.log("未完善信息跳转到完善信息页面");

		redirectToFix({
			url: "/pages/user/register?isweixin=0&from=" + from
		}, isOneKeyLogin)
	} else {
		console.log("跳转到原来源页面");
		if (from == 'moments') {
			redirectToFix({
				url: "/module_community/pages/moments/moments"
			}, isOneKeyLogin)
		} else if (from == 'article') {
			redirectToFix({
				url: '/module_community/pages/article/article'
			}, isOneKeyLogin)
		} else if (from == 'activity') {
			redirectToFix({
				url: '/module_community/pages/activity/activity'
			}, isOneKeyLogin)
		} else if (from == 'myAppointment') { //我的预约
			redirectToFix({
				url: "/module_my/pages/myAppointment/myAppointment"
			}, isOneKeyLogin)
		} else if (from == 'wishList') { //心愿单
			redirectToFix({
				url: "/module_my/pages/wishList/wishList"
			}, isOneKeyLogin)
		} else if (from == 'myorderHome') { //我的订单
			redirectToFix({
				url: "/module_my/myorderHome/myorderHome"
			}, isOneKeyLogin)
		} else if (from == 'orderList') { //我的订单
			uni.redirectToFix({
				url: "/module_my/pages/orderList/orderList"
			})
		} else if (from == 'myCarList') { //我的爱车
			redirectToFix({
				url: "/module_car/myCarList/myCarList"
			}, isOneKeyLogin)
		} else if (from == 'personalCenter') { //发布去个人中心
			redirectToFix({
				url: "/module_my/pages/personalCenter/personalCenter"
			}, isOneKeyLogin)
		} else if (from == 'following') { //跳转我的关注
			redirectToFix({
				url: "/module_my/pages/following"
			}, isOneKeyLogin)
		} else if (from == 'follower') { //跳转粉丝
			redirectToFix({
				url: "/module_my/pages/follower"
			}, isOneKeyLogin)
		} else if (from == 'myAddress') { //跳转我的地址
			redirectToFix({
				url: "/module_my/pages/myAddress/myAddress"
			}, isOneKeyLogin)
		} else {
			//from直接传递页面路由的情况
			if (from && from.length > 0 && from.indexOf('pages') != -1) {
				console.log("goBackSourcePage else redirectTo");
				redirectToFix({
					url: from
				}, isOneKeyLogin)
			} else {
				let pages = getCurrentPages(); //获取跳转的所有页面
				if (pages.length == 1) {
					console.log("goBackSourcePage else switchTab");
					uni.switchTab({
						url: "/pages/community/community",
						fail(err) {
							console.log(err, 'err')
						}
					})
				} else if (pages.length == 0) {
					//0不操作
				} else {
					console.log("goBackSourcePage else navigateBack");
					uni.navigateBack({
						changed: true
					}); //返回上一页
				}
			}
		}
	}
}
/**
 * @param {String} str (y-m-d h:i:s) y:年 m:月 d:日 h:时 i:分 s:秒
 */
function dateTimeStr(str) {
	var date = new Date(),
		year = date.getFullYear(), //年
		month = date.getMonth() + 1, //月
		day = date.getDate(), //日
		hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(), //时
		minute = date.getMinutes() < 10 ? date.getMinutes() : date.getMinutes(), //分
		second = date.getSeconds() < 10 ? date.getSeconds() : date.getSeconds(); //秒
	month >= 1 && month <= 9 ? (month = "0" + month) : "";
	day >= 0 && day <= 9 ? (day = "0" + day) : "";
	hour >= 0 && hour <= 9 ? (hour = "0" + hour) : "";
	minute >= 0 && minute <= 9 ? (minute = "0" + minute) : "";
	second >= 0 && second <= 9 ? (second = "0" + second) : "";
	if (str.indexOf('y') != -1) {
		str = str.replace('y', year)
	}
	if (str.indexOf('m') != -1) {
		str = str.replace('m', month)
	}
	if (str.indexOf('d') != -1) {
		str = str.replace('d', day)
	}
	if (str.indexOf('h') != -1) {
		str = str.replace('h', hour)
	}
	if (str.indexOf('i') != -1) {
		str = str.replace('i', minute)
	}
	if (str.indexOf('s') != -1) {
		str = str.replace('s', second)
	}
	return str;
}
// 判断页面是否在当前堆栈。
function pageExist(page) {
	var routes = getCurrentPages()
	var exist = false;
	var array = [];
	routes.forEach((item) => {
		array.push(item.route);
		if (item.route.indexOf(page) != -1) {
			exist = true;
		}
	});
	console.log("current pages" + array);
	return exist;
}
//清除ios角标 all清除所有，false的时候reduce需要大于1 减去n个角标
function clearBadge (all,reduce) {
	if (plus.os.name.toLowerCase() == 'ios') {
		console.log("clearBadge");
		//导入ios UIApplication  
		var UIApplication = plus.ios.import("UIApplication");
		var app = UIApplication.sharedApplication();
		//获取应用图标的数量  
		var oldNum = app.applicationIconBadgeNumber();
		var newNum = oldNum - reduce;
		if (newNum < 0) {
			newNum = 0;
		}
		if(all && reduce == 0){
			newNum = 0;
		}
		
		//设置应用图标的数量  
		plus.runtime.setBadgeNumber(newNum);
		//导入个推原生类  
		var GeTuiSdk = plus.ios.importClass('GeTuiSdk');
		GeTuiSdk.setBadge(newNum);
	}
}
function setBadge (num) {
	if (plus.os.name.toLowerCase() == 'ios') {
		console.log("setBadge");
		if (num < 0) {
			num = 0;
		}
		//设置应用图标的数量  
		plus.runtime.setBadgeNumber(num);
		//导入个推原生类  
		var GeTuiSdk = plus.ios.importClass('GeTuiSdk');
		GeTuiSdk.setBadge(num);
	}
}
function syncBadge(app){
	if (isLogin(app)){
		var uri=app.globalData.config.interfaces.URL_SYS_COUNTUNREAD
		var params={
			userId:app.getUserId()
		}
		network.get(uri, params, 'form').then(res => {
			
			if(res.code==200){
				var num=res.data
				console.log('!!!!!!!!!!!!!!!!!!!!!num'+res.data)
				console.log('!!!!!!!!!!!!!!!!!!!!!num'+app.getUserId())
				uni.showToast({
					title: res.data,
					duration: 3000,
					icon: 'none'
				})
				setBadge(num)
			}
		}).catch(res => {
			console.error(res)
		})
	}
}
module.exports = {
	isLogin: isLogin,
	jumpLogin: jumpLogin,
	subYMD: subYMD,
	subHMS: subHMS,
	getLocation: getLocation,
	getNavigationBarTitle: getNavigationBarTitle,
	createUidKey: createUidKey,
	dateTimeStr: dateTimeStr,
	bannerJump: bannerJump,
	goBackSourcePage: goBackSourcePage,
	gotBackSourePageMini: gotBackSourePageMini,
	pageExist: pageExist,
	compareVersion: compareVersion,
	goBackSourcePageFix: goBackSourcePageFix,
	timeFrom: timeFrom,
	clearBadge:clearBadge,
	setBadge:setBadge,
	syncBadge:syncBadge,
};
